<?php
namespace Home\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Think\Cache\Driver\Redis;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Log;


class TestController extends Controller {
    
    
    public function test(){
        
        $customerId = 6429;
        $data = D("Customer")->where(['id' => $customerId])->find();
        
        $data['need_money']=50000;//单位元 测试写死 上线屏蔽
        $data['consume_id']=3230;
        //$ret = BaseHook::executeHook("DECISION_ENGINE_HOOK", $data,5);
        
       // $ret = BaseHook::executePayWayHook("PAYWAY_ENGINE_HOOK", $data);
        var_dump($ret);
        
    }
    public function  changeBillPayLogBySearch(){
        $order_id=I("get.order_id");
        $url='http://zqhfundtest.huoyanzichan.com/RepayMoney/Pay/testSearch?requestno='.$order_id;
        $json= file_get_contents($url);
        $arr=json_decode($json,true);
        $success = $arr['errorcode']==''?'success':'failed';
        if($arr['errormsg']){
            $res=M("customer_bill_pay_log",null)->where(['order_id'=>$arr['requestno']])->setField(['ret_msg'=>$arr['errormsg']]);
            Log::pay_write("-查询易宝订单状态     订单号： ".$order_id."    结果".$success);
        }
    }
	 public function bindCardYinshengbao(){
        $CustomerId = I('get.customer_id');
        if(!$CustomerId){
            $this->ajaxReturn(['code'=>400,'msg'=>'id  not exists']);
        }
        $map = [];
        $map_ = [];
        $map['customer_id'] = $CustomerId;
        $map_['id'] = $CustomerId;
        //$map['sub_contract_id '] = '123';
        $customer = M('customer')->field('id,mobile,real_name,id_num')->where($map_)->find();
        $data = M('customer_bank_info',null)
                ->field('id,customer_id,card_user_name,sub_contract_id,card_num,reserved_mobile')
                ->where($map)
                ->find();
        if(!$data){
            echo $CustomerId.'子协议号不为123';
        }else{

        }
        echo json_encode($data);
        echo json_encode($customer);
        $card=A('Home/Pay');
        echo $data['card_num'].$data['reserved_mobile'].$data['card_user_name'].$customer['id_num'];
       // die;
        $da=$card->unsBind($data['card_num'],$data['reserved_mobile'],$data['card_user_name'],$customer['id_num']);

        echo '卡号码'.$data['card_num'].'返回结果'.json_encode($da).'<br/>';
        //$d=json_decode($da,true);
        var_dump($da);
        if($da['result_code']=='1005'){
            echo $data['card_num'].'子协议号已存在'.$da;
        }
        //{"result_code":"0000","result_msg":"","subContractId":"9384440"}
        if($da['result_code']=='0000'){
           //subContractId --9384440
            echo '0000';
            echo  json_encode($da);
            $cancel_res = M('customer_bank_info',null)->where(['customer_id'=>$CustomerId])->setField(['sub_contract_id'=>$da['subContractId']]);

        }
        

    }
	public function rm(){
		$consume_id=I('post.consume_id');
		$key='处理中订单-'.$consume_id;
		$redis = new Redis();
		Log::pay_write("--------------|开始删除:".$key.'|'.$redis->get($key));
		if($redis->get($key)){
                        $redis_res=$redis->rm($key);
                        Log::pay_write("--------------|删除redis处理中|key:".$key.'|');
                        Log::pay_write("---------删除redis处理中的结果|".$redis_res.'|');
                    }	
	}
	public function rm_(){
		echo '123';
		//$test=M('Customer')->where(['id'=>514354])->find();
		//$test2=M('CustomerBillPayLog')->where(['customer_id'=>514354])->find();
                print_r($test1);


	}
		
    	public function bank_(){
	  	echo '03';
		 $customerId='7245320';	
	    $CustomerBankInfo = M('CustomerBankInfo');
            $data_arr = $CustomerBankInfo->where("customer_id = $customerId and sub_contract_id<>''")->field('sub_contract_id')->find();
            /***************************绑定多张银行卡|finishmodel|customerbanckinfo|**********************/
            $data_arr = $CustomerBankInfo->where("sub_contract_id =".$customerId)->find();

		var_dump($data_arr);
	}
	
	public function printfRedis(){
		echo '03服务器';
                 $redis=new Redis();
                 $redis->lpush('testredis',time());
                 $list=$redis->lrange('testredis',0,-1);
                 var_dump($list);
		$arr=array();
		$arr['host']='r-m5e513a25dec5a14.redis.rds.aliyuncs.com';
		$arr['auth']='339210abC';
                 $redis=new Redis($arr);
		 var_dump($redis);
                 // sleep(1);
                 $redis->lpush('testredis',time());
                 $list=$redis->lrange('testredis',0,-1);
                var_dump($list);

		}

         public function jsonPrintf()
        {
         $arr = ['a'=>'a','b'=>'b'];
        // echo json_encode($arr);
          $this->ajaxReturn($arr);
        }

    /**
     * 找钱花用户58不同情况不同处理
     */
    public function api58()
    {
        $customerId = I('get.customer_id',0,'int');
        $sql = "select id,type,status from consume_history where customer_id = ".$customerId." order by id DESC limit 3";
        $res = M()->query($sql);
        if ($res[0]['type'] == 5 && $res[0]['status'] == 8){
            if ($res[1]['type'] == 4 && $res[1]['status'] == 12){
                $model = 'Order/orderReset';
                $xml_data = [
                    'consume_id'=>$res[0]['id'],
                    'customer_id'=>$customerId
                ];
                $test=D('Ajax')->ajaxPost($model, $xml_data);
                Log::sub_write("***loanMoney|放款|json:".json_encode($test).'|code:'.$test['code'].'|原生：'.$test);
            }
            if ($res[1]['type'] == 5 && ($res[1]['status'] == 1 || $res[1]['status'] == 3)){
                if ($res[2]['type'] == 4 && $res[2]['status'] == 12){
                    $sql1 = "delete from consume_history where type = 5 and status = 8 and customer_id = ".$customerId." limit 1";
                    $res1 = M()->query($sql1);
                    if (!empty($res1)){
                        Log::write("用户提现点击次数过多".$customerId."操作删除5---8失败");
                    }
                    $sql3 = "select cash_amount,balance_cash_amount from customer where id = ".$customerId;
                    $res3 = M()->query($sql3);
                    if ($res3[0]['cash_amount'] >= $res3[0]['balance_cash_amount']){
                        $balance_cash_amount = $res3[0]['cash_amount'];
                        $sql4 = "update customer set balance_cash_amount = ".$balance_cash_amount." where id = ".$customerId;
                        $res4 = M()->query($sql4);
                        if (!empty($res4)){
                            Log::write("用户提现点击次数过多".$customerId."操作删除用户表控制字段失败");
                        }
                    }
                }
            }
        }
    }

    /**
     * 找钱花用户冲正不同情况不同处理
     */
    public function chongzheng()
    {
        $customerId = I('get.customer_id',0,'int');
        $sql = "select id,type,status from consume_history where customer_id = ".$customerId." order by id DESC limit 2";
        $res = M()->query($sql);
        if ($res[0]['type'] == 5 && ($res[0]['status'] == 17 || $res[0]['status'] == 1)){
            if ($res[1]['type'] == 4 && $res[1]['status'] == 12){
                    $model = 'Order/orderReset';
                    $xml_data = [
                        'consume_id'=>$res[0]['id'],
                        'customer_id'=>$customerId
                    ];
                    $test=D('Ajax')->ajaxPost($model, $xml_data);
                    Log::write("***loanMoney|放款|json:".json_encode($test).'|code:'.$test['code'].'|原生：'.$test);

            }
        }
    }

    public function fixBug()
    {
        $sql = "SELECT mobile FROM customer WHERE tongdun_device_id = 'Rong360' and id_num = '' AND mobile like '1%'";
        $res = M()->query($sql);
        foreach ($res as $key => $value) {
            $mobile = $value['mobile'];
            Log::write("mmmmmmmmmmm|mobile|". $mobile);
            $this->fixBugStep($mobile);
        }
    }

    public function fixBugStep($mobile)
    {
        $trueCustomerFind = M("Customer")->field("id")->where("mobile = $mobile and id_num != ''")->find();
        $trueCustomerId = $trueCustomerFind['id'];
        $falseCustomerFind = M("Customer")->field("id")->where("mobile = $mobile and id_num = ''")->find();
        $falseCustomerId = $falseCustomerFind['id'];
        
        $mobile = (string)$mobile;
        $mobile = preg_replace('/1/','2',$mobile,1);
        $mobile = (int)$mobile;

        $setCRes = M("Customer")->where("id = '$falseCustomerId'")->setField(['mobile'=>$mobile]);
        $setCHRes = M("ConsumeHistory")->where("customer_id = $falseCustomerId")->setField(['customer_id'=>$trueCustomerId]);
        $setTCHRes = M("ThirdpartyConsumeHistory")->where("customer_id = $falseCustomerId")->setField(['customer_id'=>$trueCustomerId]);
        Log::write("mmmmmmmmmmm|falseCustomerId|". $falseCustomerId ."|trueCustomerId|". $trueCustomerId ."|setCRes|". $setCRes ."|setCHRes|". $setCHRes ."|setTCHRes|". $setTCHRes);
    }

    /*根据订单号查询是否扣款成功*/
    public function Xujie(){
        $order_id=I('get.orderId');
        $CustomerBillPayLog = M('CustomerBillPayLog');
        $aa=$CustomerBillPayLog->field("id,order_id,consume_id,customer_id")->where(['order_id'=>$order_id])->find();
        $consume_id=$aa['consume_id'];
        $insertId=$aa['id'];
        $customerId=$aa['customer_id'];
        $pay=A('Home/Pay');
        $resultstatu = $pay->unsPaystatu($order_id);
       /*查询是否扣款成功*/
        Log::pay_write('**********手动查询 用户'.$customerId.'   '.$order_id.'续借执行查询是否实际扣款返回结果：'.$resultstatu.json_encode($resultstatu));
        $redis =new Redis();
        if($resultstatu['status'] == '00'){
            if($redis->get('yigenggai-'.$order_id)){
                Log::pay_write('**********手动查询 用户'.$customerId.' 订单号  '.$order_id.' 已经执行过一次 key:'.'yigenggai-'.$order_id.'  value:'.$redis->get('yigenggai-'.$order_id));
                return ;

            }
            //还款成功写库
            $sqldata = array('trade_state'=>$resultstatu['result_msg'],'ret_msg'=>'success','pay_time'=>time(),'ret_code'=>$resultstatu['result_code'],'status'=>1);
            $test1=$CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
            Log::pay_write('**********手动查询 用户'.$customerId.'实际还款成功入库：CustomerBillPayLog:结果'.json_encode($test1));
            $CustomerBillPayLogInfo = $CustomerBillPayLog->where(['order_id' => $order_id])->find();
            $consume_id = $CustomerBillPayLogInfo['consume_id'];
            $customer_id = $CustomerBillPayLogInfo['customer_id'];
            $ConsumeHistory = M('consume_history')->where(['id' => $consume_id])->find();
            Log::pay_write('**********手动查询  用户'.$customerId.'实际还款成功入库：consume_id:结果'.$consume_id);
            if($consume_id>0) {
                /****这里扣款成功修改status给贷后分单用，防止撤单分单出现已还款仍能撤分单***/
                $ConsumeUserInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->find();
                if (isset($ConsumeUserInfo) && !empty($ConsumeUserInfo)) {
                    $ConsumeUserStatusInfo = M('consume_user')->where("consume_id = $consume_id and status = 1")->setField(array('status'=>3));//状态3表示逾期续借
                }
                $repay_time=  M('ConsumeHistory')->where(['id'=>$consume_id])->field('repayment_time,repay_id')->find();
                $repay_time_=  M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->field('repayment_time')->find();
                //之前还款时间
                $repay_time_old=$repay_time_['repayment_time'];
                if(!$repay_time_old){//如果不存在|默认取当前当前
                    $repay_time_old=time();
                }
                $repay_time['repay_id']=($repay_time['repay_id']==1)?3:$repay_time['repay_id'];
                $repay_long = M('SysInstallmentPlan')->where(['id' =>  $repay_time['repay_id'], 'publish' => 1, 'target' => 3])->find();
                $test4=M('Customer')->where(['id'=>$customer_id])->setField(['balance_cash_amount'=>100000]);
                /***|该次展期成功|展期控制状态归0,修改账单|***/
                M('ConsumeHistory')->where(['id'=>$consume_id])->setField(['repayment_time'=>$repay_time_old+$repay_long['timer']*24*3600,'renew_id'=>$ConsumeHistory['renew_id']+1]);
                M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id])->setField(['update_time'=>time(),'repayment_time'=>$repay_time_old+$repay_long['timer']*24*3600,'allow_renew'=>0]);
                $redis->set('yigenggai-'.$order_id,'done',60*60*12);//60
                Log::pay_write('**********手动查询  修改成功 设置redis 防止重复修改数据库'.$customerId.' '.$consume_id.' redis  key '.'yigenggai-'.$order_id.'  redis  value:'.$redis->get('yigenggai-'.$consume_id));
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
            /*查询是否扣款成功*/
        }else if($resultstatu['status'] == '20'){
            $status = 3;
            $sqldata = array('ret_msg'=>'银行卡余额不足','ret_code'=>1111,'status'=>$status);
            $CustomerBillPayLog->where(['id'=>$insertId,'status'=>0])->setField($sqldata);
            //手动输入的预扣金额为零
            M('ConsumeInstallmentHistory')->where(['parent_id'=>$consume_id,'update_time'=>0])->setField(["final_amount"=>0]);
            $this->ajaxReturn(['code' => 1111, 'msg' => '银行卡上余额不足']);
            /**********************************/
        }elseif($resultstatu['status'] == '10'){
            $this->ajaxReturn(['code' => 10, 'msg' => '正在续借，请稍后']);
        }
    }
}
